package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.dao.AttrDao;
import com.atguigu.gmall.pms.dao.SkuInfoDao;
import com.atguigu.gmall.pms.dao.SpuInfoDescDao;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.SkuSaleFeign;
import com.atguigu.gmall.pms.service.ProductAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SkuSaleAttrValueService;
import com.atguigu.gmall.pms.vo.ProductAttrValueVO;
import com.atguigu.gmall.pms.vo.SkuInfoVO;
import com.atguigu.gmall.pms.vo.SpuInfoVO;
import com.atguigu.gmall.sms.feign.GmallSmsApi;
import com.atguigu.gmall.sms.vo.SkuSaleVO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;

import com.atguigu.gmall.pms.dao.SpuInfoDao;
import com.atguigu.gmall.pms.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuSaleFeign skuSaleFeign;

    @Autowired
    private AmqpTemplate amqpTemplate;


    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageVo(page);
    }

    /**
     * 查询商品列表
     * @param queryCondition
     * @param catId
     * @return
     */
    @Override
    public PageVo querySpuInfo(QueryCondition queryCondition, Long catId) {
        //封装分页条件
        IPage<SpuInfoEntity> page = new Query<SpuInfoEntity>().getPage(queryCondition);
        //封装查询条件
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        //若catId==0，则查询全部类
        if (catId != 0) {
            queryWrapper.eq("catalog_id",catId);
        }
        // 如果用户输入了检索条件，根据检索条件查（在查本类还是查全站条件下，根据商品id或商品名查询）
        String key = queryCondition.getKey();
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(wrapper->wrapper.eq("id",key).or().like("spu_name",key));
        }

        return new PageVo(this.page(page,queryWrapper));
    }

    /**
     * 1.spu商品保存接口
     * 2.图片信息
     * 3. 基本属性信息
     * 4.sku信息
     * 5.营销，满减，打折，使用feign调用gmall-sms
     * @param spuInfoVO
     */
    @Override
    @GlobalTransactional
    public void saveSpuInfoVO(SpuInfoVO spuInfoVO) {
        //保存spu相关
        //1.1保存spu基本信息pms_spu_info
        spuInfoVO.setPublishStatus(1);
        spuInfoVO.setCreateTime(new Date());
        spuInfoVO.setUodateTime(spuInfoVO.getCreateTime());
        this.save(spuInfoVO);
        //新增后回显spuId
        Long spuId = spuInfoVO.getId();

        //保存spu的描述信息 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(StringUtils.join(spuInfoVO.getSpuImages(),","));
        this.spuInfoDescDao.insert(spuInfoDescEntity);

        //1.3保存spu的规格参数信息，pms_product_attr_value
        List<ProductAttrValueVO> baseAttrs = spuInfoVO.getBaseAttrs();
        if (! baseAttrs.isEmpty()) {
            List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(productAttrValueVO -> {
                productAttrValueVO.setSpuId(spuId);
                productAttrValueVO.setAttrSort(0);
                productAttrValueVO.setQuickShow(0);
                return productAttrValueVO;

            }).collect(Collectors.toList());
            this.productAttrValueService.saveBatch(productAttrValueEntityList);
        }

        //2.保存sku相关信息
        List<SkuInfoVO> skuInfoVOList = spuInfoVO.getSkus();
        if (skuInfoVOList.isEmpty()) {
            return;
        }
        skuInfoVOList.forEach(skuInfoVO -> {
            //2.1保存sku基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(skuInfoVO,skuInfoEntity);
            // 品牌id和分类的id需要从spuInfo中获取
            skuInfoEntity.setBrandId(spuInfoVO.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoVO.getCatalogId());
            // 获取随机的uuid作为sku的编码
            skuInfoEntity.setSkuCode(UUID.randomUUID().toString().substring(0, 10).toUpperCase());
            //获取图片列表
            List<String> imageList = skuInfoVO.getImages();
            //如果图片列表不为null，则设置为默认图片
            if (! imageList.isEmpty()) {
                skuInfoEntity.setSkuDefaultImg(skuInfoEntity.getSkuDefaultImg() == null ? imageList.get(0) : skuInfoEntity.getSkuDefaultImg());
            }
            skuInfoEntity.setSpuId(spuId);
            this.skuInfoDao.insert(skuInfoEntity);
            //获取回显的skuId
            Long skuId = skuInfoEntity.getSkuId();

            //2.2保存sku图片信息
            if (! imageList.isEmpty()) {
                String skuDefaultImg = skuInfoEntity.getSkuDefaultImg();
                List<SkuImagesEntity> skuImagesEntityList = imageList.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(StringUtils.equals(skuDefaultImg, image) ? 1 : 0);
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setImgUrl(image);
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                this.skuImagesService.saveBatch(skuImagesEntityList);
            }

            //2.3保存sku的规格参数（销售属性）
            List<SkuSaleAttrValueEntity> saleAttrsList = skuInfoVO.getSaleAttrs();
            saleAttrsList.forEach(saleAttr->{
                //设置属性名,根据id查询AttrEntity
//                saleAttr.setAttrName(this.attrDao.selectById(saleAttr.getId()).getAttrName());
                saleAttr.setAttrSort(0);
                saleAttr.setSkuId(skuId);
            });
            this.skuSaleAttrValueService.saveBatch(saleAttrsList);

            //3.保存营销相关信息，需要远程调用gmall-sms
            SkuSaleVO skuSaleVO = new SkuSaleVO();
            BeanUtils.copyProperties(skuInfoVO,skuSaleVO);
            skuSaleVO.setSkuId(skuId);
            this.skuSaleFeign.saveSkuSaleInfo(skuSaleVO);

        });
        //增加运行时错误，测试全局事务
        //int i = 1 / 0;

        //异步发送消息通知ES进行新增商品
        sendMessage(spuId,"insert");
    }


    /**
     * MQ异步消息发送
     * @param spuId
     * @param type
     */
    private void sendMessage(Long spuId,String type) {

        try {
            //使用默认的交换机
            amqpTemplate.convertAndSend("item." + type,spuId);
        } catch (AmqpException e) {
            log.error("异步消息发送失败");
        }
    }

}